package com.example.wxg.stream.custom.sink;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.redis.RedisSink;
import org.apache.flink.streaming.connectors.redis.common.config.FlinkJedisPoolConfig;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisCommand;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisCommandDescription;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisMapper;

/**
 * @author void
 * @date 2021/11/12 14:22
 * @desc
 */
public class RedisSinkTest {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment evn = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource<String> text = evn.socketTextStream("devtwo", 9800, "\n");
        
        //数据组装
        DataStream<Tuple2<String,String>> wordsData = text.map(new MapFunction<String, Tuple2<String,String>>() {
            @Override
            public Tuple2<String, String> map(String s) throws Exception {
                //组装数据时redis的key永远是words，value则为socket输入的单词
                return new Tuple2<>("words", s);
            }
        });
        
        //redis配置
        FlinkJedisPoolConfig config = new FlinkJedisPoolConfig.Builder().setHost("172.16.1.100").setPort(6379).setDatabase(0).build();
        RedisSink<Tuple2<String, String>> redisSink = new RedisSink<>(config, new MyRedisMapper());
        
        wordsData.addSink(redisSink);
        evn.execute("redis sink 启动");
    }

    /**
     * 自定义redis处理逻辑
     */
    public static class MyRedisMapper implements RedisMapper<Tuple2<String, String>>{

        @Override
        public RedisCommandDescription getCommandDescription() {
            return new RedisCommandDescription(RedisCommand.LPUSH);
        }

        /**
         * 表示从接收的数据中获取需要操作的redis key
         * @param data
         * @return
         */
        @Override
        public String getKeyFromData(Tuple2<String, String> data) {
            System.out.println("redis的key名:"+data.f0);
            return data.f0;
        }

        /**
         * 表示从接收的数据中获取需要操作的redis value
         * @param data
         * @return
         */
        @Override
        public String getValueFromData(Tuple2<String, String> data) {
            System.out.println("redis的value值:"+data.f1);
            return data.f1;
        }
    }
}
